package com.youqingkuang.ipmsg.ui;

import java.util.ArrayList;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public final class Config implements Serializable {

    private static final long serialVersionUID = 2463977378376293043L;

    public String nickname = "";
    public String groupname = "";
    public String password = "";
    public ArrayList<String> addresses = null;
    public boolean checkSealing = false;
    public boolean popMsg = true;
    public boolean voiceless = true;
    public boolean sealing = false;
    public boolean citing = true;
    public boolean record = false;

    private static Config config = null;

    static public Config getInstance() {
        if (config == null) {
            File file = new File(StringToken.CONFIG_PATH);
            if (file.exists()) {
                ObjectInputStream input = null;
                try {
                    input = new ObjectInputStream(new FileInputStream(file));
                    config = (Config)input.readObject();
                    input.close();
                } catch (Exception e) {
                    config = new Config();
                    if (input != null) {
                        try {
                            input.close();
                        } catch (IOException ex) {
                            ex.printStackTrace();
                        }
                    }
                    file.delete();
                }
            } else {
                config = new Config();
            }
        }
        return config;
    }

    public void save() {
        File file = new File(System.getProperty("user.home") + StringToken.CONFIG_PATH);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        ObjectOutputStream output = null;
        try {
            output = new ObjectOutputStream(new FileOutputStream(file));
            output.writeObject(this);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (output != null) {
                try {
                    output.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private Config() {
    }

    protected void finalize() throws Throwable {
        save();
    }

}
